package com.softqin.washer.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

/**
 *creator    ：      ruan
 *create date：     2015年1月15日
 *description：     文件操作util
 */
public class FileUtils {
	private static String COMMON_DIRECTORY = "wash";	//一般存储目录
	private static String LOG_DIRECTORY    = "washlog";	//log存储目录
	
	public static void writeLog(Context context, String tag, String content) {
        String filepath = getFileDir(context, LOG_DIRECTORY);
        File sampleDir = new File(filepath);
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        String logfile = sampleDir.getAbsolutePath() + File.separator + "alarmReceiver.log";
        try {
            OutputStream mOut = new FileOutputStream(logfile, true);
            String str = "\n" + Utility.getDateTimeStamp() + tag + " : " + content;
            byte[] strBuffer = str.getBytes();
            mOut.write(strBuffer);
            mOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	/**
	 * 获取我们程序在手机上创建的目录
	 * get the directory we created on the phone
	 * @param context
	 * @param paramPathdir 需要定位到什么目录或者创建什么目录，paramPathdir就写上对应的名字
	 * @return
	 */
	public static String getFileDir(Context context, String paramPathdir) {
        String pahtdir = null;
        if (isSDCardAvailable() && isStorageAvailable()) {
            pahtdir = Environment.getExternalStorageDirectory() + File.separator + paramPathdir;
        } else {
            pahtdir = context.getCacheDir().getPath() + File.separator + paramPathdir;
        }
        return pahtdir;
    }
	
	/**
	 * 判断sd卡是否可用
	 * juedge the sd card is available
	 * @return
	 */
	public static boolean isSDCardAvailable() {
        boolean isAvailable = false;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            isAvailable = true;
        }
        return isAvailable;
    }
	
	/**
     * 判断sd卡是否有可用空间
     * judge the sd card is storage available
     */
    public static boolean isStorageAvailable() {
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        // 获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        // 空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        // 返回SD卡空闲大小
        long freeStorage = (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
        if (freeStorage > 1) {
            return true;
        }
        return false;

    }
	
}
